from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponse
import re


class MyMiddleware(MiddlewareMixin):
    visit_times = {}

    def process_request(self, request):
        print('--process_request1 do--')
        print(request.META['REMOTE_ADDR'])  # 获取访问的IP
        print(request.path_info)  # 获取访问的路由
        ip_addr = request.META['REMOTE_ADDR']
        path_url = request.path_info
        if not re.match('^/test', path_url):
            return
        times = self.visit_times.get(ip_addr, 0)
        print('ip:' + ip_addr + ' times:' + str(times+1))
        self.visit_times[ip_addr] = times + 1
        if times < 5:
            return
        return HttpResponse('当前IP已访问过' + str(times) + '次，访问被禁止')


    def process_view(self, request, view_func, view_args, view_kwargs):
        print(view_func.__name__)
        print('--process_view1 do--')

    def process_response(self, request, response):
        print('--process_response1 do--')
        return response

    def process_exception(self, request, exception):
        print('--process_exception1 do--')
        return HttpResponse(str(exception), status=500)


class MyMiddleware2(MiddlewareMixin):
    def process_request(self, request):
        print('--process_request2 do--')

    def process_view(self, request, view_func, view_args, view_kwargs):
        print('--process_view2 do--')

    def process_response(self, request, response):
        print('--process_response2 do--')
        return response
